import axios, { type AxiosResponse } from 'axios';
import { useAuthStore } from '@/store';
import { ElMessage } from 'element-plus';
import { router } from '@/router';

const service = axios.create({
  baseURL: '/node',
});

service.interceptors.request.use(
  (config) => {
    const token = useAuthStore().token;
    if (token)
      config.headers.Authorization = token;
    return config;
  },
  (error) => {
    return Promise.reject(error.response);
  },
);

service.interceptors.response.use(
  (response: AxiosResponse): AxiosResponse => {
    if (response.data.code === 403 && response.data.data === '/auth/sign-in.html') {
      ElMessage({
        type: 'warning',
        message: '用户登录状态已过期，请重新登录',
      });
      router.push('/login');
    }
    if (response.status === 200 && response.data?.code === -1) {
      console.log(response);
      throw new Error(response.data?.message || response.data?.msg);
    }
    if (response.status === 200 && (response.data.code >= 0 || response.data.errcode === 0) ) {
      return response;
    }
    console.log(response);
    throw new Error(response.status.toString());
  },
  (error) => {
    // if (error.response?.status === 403 || error.response?.status === 401) {
    //   ElMessage({
    //     type: 'warning',
    //     message: '用户登录状态已过期，请重新登录',
    //   });
    //   router.push('/login');
    // }
    console.log(error);
    return Promise.reject(error);
  },
);

export default service;
